#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <ESP8266HTTPClient.h>

#define SCREEN_WIDTH 128  // OLED显示宽度（像素）
#define SCREEN_HEIGHT 64  // OLED显示高度（像素）

// 使用软件SPI连接的SSD1306显示器声明（默认情况下）：
#define OLED_MOSI 5    //DI   ------ D1
#define OLED_CLK 4     //D0  ------- D2
#define OLED_DC 14     //DC  ------- D5
#define OLED_CS 12     //CS  ------- D6
#define OLED_RESET 13  //RES -------D7

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT,
                         OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, -1);

#define PIN_COUNT 6

#define PIN_INPUT 16 // D0

const int gPins[] = {
  0, // D3
  1, // TX
  2, // D4
  3, // RX
  12,// D6
  15 // D8
};

const char* ssid = "lang";
const char* password = "11235813";

const char* host = "124.71.34.101";
const int httpsPort = 5432;
const String url = "/getStatus/1.0?status={\"13\":1}";
const String fullUrl = "http://124.71.34.101:5432/getStatus/1.0";

unsigned char wifi_connect_process = 0;

unsigned short current_fetch_interval = 1000;

unsigned short fetchCounter = 0;

unsigned int current_pin_state = 0;

void setup() {
  Serial.begin(9600);

  // SSD1306_SWITCHCAPVCC = 内部产生3.3V的显示电压
  if (!display.begin(SSD1306_SWITCHCAPVCC)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;)
      ;  // 不要继续，一直循环
  }
  //在屏幕上显示初始显示缓冲区内容库用Adafruit启动屏幕初始化。
  display.display();

  // 清空缓冲区
  display.clearDisplay();

  // 用白色绘制单个像素
  display.drawPixel(10, 10, WHITE);

  // 在屏幕上显示显示缓冲区。必须在绘制命令后调用display（），使其在屏幕上可见！
  display.display();

  delay(2000);

  Serial.println();
  Serial.print("connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

  for (int i = 0; i < PIN_COUNT; i++) {
    pinMode(gPins[i], OUTPUT);
  }
  
  pinMode(PIN_INPUT, PIN_INPUT);
}

void loop() {
  int pinState = current_pin_state++ % 2 == 0;
 
  for (int i = 0; i < PIN_COUNT; i++) {
    digitalWrite(gPins[i], pinState);
  }

  if (WiFi.status() != WL_CONNECTED) {
    showConnecting();
  } else {
    fetchRemoteConfigAndApply();
  }
}

void showConnecting() {
  unsigned char process = (wifi_connect_process++) % 4;

  display.clearDisplay();

  display.setTextSize(1);       // 正常1:1像素比例
  display.setTextColor(WHITE);  // 绘制白色文本
  display.setCursor(0, 0);      // Start at top-left corner

  if (process == 0) {
    display.println("Wifi Connecting");
  } else if (process == 1) {
    display.println("Wifi Connecting.");
  } else if (process == 2) {
    display.println("Wifi Connecting..");
  } else {
    display.println("Wifi Connecting...");
  }

  display.display();

  delay(1000);
}

void fetchRemoteConfigAndApply() {
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0, 0);

  if (fetchCounter++ % 2 == 0) {
    display.println(">>>");
  } else {
    display.println("<<<");
  }

  if (digitalRead(PIN_INPUT) == HIGH) {
    display.println("Body detedted");
  } else {
    display.println("No body detedted");
  }

  doHttpGet();

  display.display();

  delay(current_fetch_interval);
}

void doHttpGet() {
  WiFiClient client;
  HTTPClient http;

  http.begin(client, fullUrl);

  int code = http.GET();
  if (code == HTTP_CODE_OK) {
	  String resp = http.getString();
    display.println(resp);
  } else {
    display.println("Http get failed!");
  }
  http.end();
}
